package com.luocc.inputdemo.watcher

import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.widget.EditText
import android.widget.Toast

/**
 * 表情、中文字符、字母，三者的长度是不一样的
 * 一个数字或字母：     1 byte
 * 一个中文：          3 byte
 * 一个表情：          4 byte
 *
 * 表情在onTextChanged中的count只占2，中文占1，字母占1
 *
 */
class Watcher2(private val editText: EditText, private val limit: Int, private val TAG: String) :
    TextWatcher {
    private val change = IntArray(2)
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        Log.d(TAG, "beforeTextChanged")
    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        Log.d(TAG, "onTextChanged s = $s, start = $start, before = $before, count = $count")
        if (!suitable(s.toString())) {
            change[0] = start
            change[1] = start + count
        }
    }

    override fun afterTextChanged(s: Editable?) {
        Log.d(TAG, "afterTextChanged")
        if (!suitable(s.toString())) {
            s?.let {
                // 注意substring的参数范围
                val start = s.substring(0, change[0])
                Log.d(TAG, "afterTextChanged: start =  $start")
                val end = s.substring(change[1], s.length)
                Log.d(TAG, "afterTextChanged: end = $end")
                val text = start + end
                // 会继续调用before、on、after
                editText.setText(text)
                editText.setSelection(change[0])
                handler.removeCallbacks(runnable)
                handler.postDelayed(runnable, 100)
            }
        }
        Log.d(TAG, "afterTextChanged: s = $s")
    }

    /**
     * Determine whether the current input is legal
     */
    private fun suitable(str: String): Boolean {
        val size = str.toByteArray().size
        Log.d(TAG, "suitable: size = $size")
        return size <= limit
    }

    private val handler = object : Handler(Looper.getMainLooper()) {}
    private val runnable =
        Runnable {
            Toast.makeText(editText.context, "限制 $limit byte!", Toast.LENGTH_SHORT).show() }
}